package com.xiuxia.bopicturebackend.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiuxia.bopicturebackend.annotation.CheckAuth;
import com.xiuxia.bopicturebackend.common.BaseResponse;
import com.xiuxia.bopicturebackend.common.DeleteRequest;
import com.xiuxia.bopicturebackend.common.ResultUtils;
import com.xiuxia.bopicturebackend.constant.UserConstant;
import com.xiuxia.bopicturebackend.exception.BusinessException;
import com.xiuxia.bopicturebackend.exception.ErrorCode;
import com.xiuxia.bopicturebackend.exception.ThrowUtils;
import com.xiuxia.bopicturebackend.model.dto.space.SpaceAddRequestDTO;
import com.xiuxia.bopicturebackend.model.dto.user.*;
import com.xiuxia.bopicturebackend.model.entity.User;
import com.xiuxia.bopicturebackend.model.vo.user.UserInfoVO;
import com.xiuxia.bopicturebackend.model.vo.user.UserLoginVO;
import com.xiuxia.bopicturebackend.model.vo.user.UserVO;
import com.xiuxia.bopicturebackend.service.SpaceService;
import com.xiuxia.bopicturebackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "userController")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private SpaceService spaceService;

    /**
     * 用户注册接口
     */
    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    @Transactional
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequestDTO userRegisterRequestDTO) {
        ThrowUtils.throwIf(userRegisterRequestDTO==null,new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空"));
        long userId = userService.userRegister(userRegisterRequestDTO);
        spaceService.addSpace(new SpaceAddRequestDTO(),userService.getById(userId));
        return ResultUtils.success(userId);
    }

    /**
     * 用户登录接口
     */
    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public BaseResponse<UserLoginVO> userLogin(@RequestBody UserLoginRequestDTO userLoginRequestDTO, HttpServletRequest request) {
        ThrowUtils.throwIf(userLoginRequestDTO==null,new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空"));
        String userAccount = userLoginRequestDTO.getUserAccount();
        String userPassword = userLoginRequestDTO.getUserPassword();

        return ResultUtils.success(userService.userLogin(userAccount, userPassword, request));
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/get/loginUser")
    @ApiOperation("获取当前登录用户信息接口")
    public BaseResponse<UserLoginVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        UserLoginVO userLoginVO = userService.getUserLoginVO(loginUser);
        return ResultUtils.success(userLoginVO);
    }
    @PostMapping("/logout")
    @ApiOperation("用户登出接口")
    public BaseResponse<Boolean> userLogout(HttpServletRequest request) {
        return ResultUtils.success(userService.userLogout(request));
    }
    /**
     * 创建用户
     */
    @PostMapping("/add")
    @ApiOperation("创建用户接口")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequestDTO userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        // 默认密码 12345678
        final String DEFAULT_PASSWORD = "12345678";
        String encryptPassword = userService.getEncryptPassword(DEFAULT_PASSWORD);
        user.setUserPassword(encryptPassword);
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(user.getId());
    }

    /**
     * 根据 id 获取用户（仅管理员）
     */
    @GetMapping("/get")
    @ApiOperation("根据 id 获取用户（仅管理员）接口")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<User> getUserById(long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        User user = userService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     */
    @ApiOperation("根据 id 获取包装类接口")
    @GetMapping("/get/vo")
    public BaseResponse<UserVO> getUserVOById(long id) {
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户（仅管理员）接口")
    @PostMapping("/delete")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     */
    @PostMapping("/update")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    @ApiOperation("更新用户（仅管理员）接口")
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequestDTO userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean result = userService.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 分页获取用户封装列表（仅管理员）
     *
     * @param userQueryRequest 查询请求参数
     */
    @PostMapping("/list/page/vo")
    @ApiOperation("分页获取用户封装列表（仅管理员）接口")
    @CheckAuth(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserVO>> listUserVOByPage(@RequestBody UserQueryRequestDTO userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryRequest));
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOList);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 获取用户信息(用户个人中心)
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/get/userInfo")
    public BaseResponse<UserInfoVO> getUserInfoVO(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtil.copyProperties(loginUser, userInfoVO);
        return ResultUtils.success(userInfoVO);
    }
    /**
     * 更新用户信息(用户个人中心)
     */
    @ApiOperation("更新用户信息")
    @PostMapping("/updateUserInfo")
    public BaseResponse<Boolean> updateUserInfo(@RequestBody UserInfoUpdateRequestDTO userInfoUpdateRequest,HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        loginUser.setUserAvatar(userInfoUpdateRequest.getUserAvatar());
        loginUser.setUserName(userInfoUpdateRequest.getUserName());
        loginUser.setUserProfile(userInfoUpdateRequest.getUserProfile());
        boolean result = userService.saveOrUpdate(loginUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(result);
    }

    /**
     * 获取所有用户信息
     * @return List<UserVO>
     */
    @GetMapping("/getAllUserVOInfo")
    @ApiOperation("获取所有用户信息")
    public BaseResponse<List<UserVO>> getAllUserVOInfo() {
        List<User> userList = userService.list();
        List<UserVO> userVOList = userService.getUserVOList(userList);
        return ResultUtils.success(userVOList);
    }

}
